import common from '../../tnxet-common.js';
import util from '../main-util.js';
import fs from 'fs';
import path from 'path';

export default {
    name: common.event.file.delete,
    listen(filePath, deleteEmptyDir, throwIfAbsent) {
        return new Promise((resolve, reject) => {
            if (filePath) {
                filePath = util.file.getAbsolutePathBasedOnApp(filePath);
                if (fs.existsSync(filePath)) {
                    fs.rm(filePath, {recursive: true, force: true}, error => {
                        if (error) {
                            reject(new Error(`Failed to delete file: ${error.message}`));
                        } else {
                            if (deleteEmptyDir) {
                                // 递归删除空目录
                                const deleteDirIfEmpty = (dir) => {
                                    try {
                                        if (dir) {
                                            const files = fs.readdirSync(dir);
                                            if (files.length === 0) {
                                                fs.rmdirSync(dir);
                                                const parentDir = path.dirname(dir);
                                                deleteDirIfEmpty(parentDir);
                                            }
                                        }
                                    } catch (e) {
                                        // 忽略删除目录时的错误
                                        console.warn(`Failed to delete empty directory ${dir}: ${e.message}`);
                                    }
                                };
                                let currentDir = path.dirname(filePath);
                                deleteDirIfEmpty(currentDir);
                            }
                            resolve();
                        }
                    });
                } else if (throwIfAbsent) {
                    reject(new Error('File not exists: ' + filePath));
                } else {
                    resolve();
                }
            } else {
                reject(new Error('Invalid filePath: ' + filePath));
            }
        });
    },
}
